package api

import (
	"encoding/json"
	"net/http"

	"shqsoft.cn/pasnj/bi/query"

	log "github.com/sirupsen/logrus"

	"github.com/labstack/echo"
)

//Query 查询
func Query(c echo.Context) error {
	res, err := queryRequest(c)
	if err != nil {
		return err
	}
	log.Print(res.Columns)
	log.Print(res.DataList)
	return c.JSON(http.StatusOK, res)
}

//Export 导出
func Export(c echo.Context) error {
	caption := "数据导出"
	res, err := queryRequest(c)
	if err != nil {
		return err
	}
	xlsx := NewXlsx(res)
	buff, err := xlsx.Export()
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	fileName := caption + ".xlsx"
	c.Response().Header().Set("Content-Type", "application/vnd.ms-excel")
	c.Response().Header().Set("Content-Disposition", "attachment; filename="+fileName)
	c.Response().Write(buff.Bytes())
	return nil
}
func queryRequest(c echo.Context) (*query.Response, error) {
	que := c.FormValue("query")
	if que == "" {
		return nil, echo.NewHTTPError(http.StatusBadRequest, "query不能为空！")
	}
	var req query.Request
	if err := json.Unmarshal([]byte(que), &req); err != nil {
		return nil, echo.NewHTTPError(http.StatusBadRequest, "解析请求出错！"+err.Error())
	}
	res, err := query.CreateResultMap(&req)
	if err != nil {
		return nil, echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	return res, nil
}
